﻿#include "mainwindow.h"
#include "ui_MainWindow.h"


MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent), ui(new Ui::MainWindow) {
    ui->setupUi(this);

    axisX = new QValueAxis();
    axisY = new QValueAxis();

    axisX->setTitleText("X_label");
    axisY->setTitleText("Y_label");

    axisX->setRange(0, 10);
    axisY->setRange(0, 10);

    axisX->setTickCount(5);

    splineSeries = new QSplineSeries();
    splineSeries->setName("spline");


    chart = new QChart();
    chart->addAxis(axisX, Qt::AlignLeft);
    chart->addAxis(axisY, Qt::AlignBottom);

    chart->legend()->hide();
    chart->addSeries(splineSeries);
    chart->setAnimationOptions(QChart::AllAnimations);

    splineSeries->attachAxis(axisX);
    splineSeries->attachAxis(axisY);


    chartView = new QChartView(chart);
    chartView->setRenderHint(QPainter::Antialiasing);

    auto *boxLayout = new QVBoxLayout(ui->frameChart);
    boxLayout->addWidget(chartView);

    QObject::connect(&timer, &QTimer::timeout, this, &MainWindow::handleTimeout);
    QObject::connect(ui->btnStart, &QPushButton::clicked, this, &MainWindow::start);
    QObject::connect(ui->btnStop, &QPushButton::clicked, this, &MainWindow::stop);

    timer.setInterval(500);
}

MainWindow::~MainWindow() {
    delete ui;
}

void MainWindow::handleTimeout() {
    int count = splineSeries->points().size();

    if (count > 10) {
        chart->axisX()->setMax(count);
    }

    splineSeries->append(QPointF(count, rand() % 10));

    chart->scroll(count, 0);
}

void MainWindow::start() {
    timer.start();

}

void MainWindow::stop() {
    timer.stop();
}
